<?php

declare (strict_types=1);

namespace App\Model;

/**
 * @property int $id
 * @property int $uid
 * @property string $username
 * @property string $nickname
 * @property string $password
 * @property int $status
 * @property int $create_time
 * @property int $online
 */
class ChatUser extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'chat_user';
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];
    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = ['id' => 'integer', 'uid' => 'integer', 'status' => 'integer', 'create_time' => 'integer', 'online' => 'integer'];

    /**
     * 增加聊天用户本地 （仅限本地，环信+声网 需要再额外注册第三方）
     * @param int $uid
     * @return bool
     */
    public static function addUser(int $uid)
    {

        $exists = ChatUser::where(['uid' => $uid])->exists();
        if ($exists) {
            return true;
        }
        $userInfo = User::where(['id' => $uid])->select('num', 'nickname')->first();

        if (is_null($userInfo)) {
            return false;
        }

        $insert = [
            'uid' => $uid,
            'username' => $userInfo['num'],
            'nickname' => $userInfo['nickname'],
            'password' => md5($userInfo['num'] . time()),
            'status' => 1,
            'create_time' => time()
        ];

        try {
            $rel = self::insert($insert);
            if ($rel) {
                return true;
            }
        } catch (\Exception $e) {
            var_dump($e->getMessage());
        }
        return false;

    }
}
